package execmd

import (
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
	"strings"
	"time"

	"github.com/Pallinder/go-randomdata"
	"gopkg.in/yaml.v2"
)

type Config struct {
	Services []*Exectab `json:"services" yaml:"services"`
	//Plugins       map[string]interface{}            `yaml:",inline"` // all unparsed means plugins
	//loadedPlugins map[string]plugins.PluginConfigNG `yaml:"-"`
}

// 归并cmd配置
func (c *Config) MergeFrom(other *Config) {
	c.Services = append(c.Services, other.Services...)
}


func DefaultConfig() Config {
	return Config{}
}

// 补充默认
func FillDefaultExecutable(exec *Exectab) {
	if exec.StopTimeout == 0 {
		exec.StopTimeout = 5 * time.Second
	}
	if exec.Name == "" {
		exec.Name = randomdata.Noun() + "-" + randomdata.Adjective()
	}
}

func LoadConfig(locations ...string) (*Config, error) {
	c := DefaultConfig()
	ans := &c
	var files []os.FileInfo
	for _, location := range locations {
		if stat, err := os.Stat(location); err != nil {
			return nil, err
		} else if stat.IsDir() {
			fs, err := ioutil.ReadDir(location)
			if err != nil {
				return nil, err
			}
			files = fs
		} else {
			location = filepath.Dir(location)
			files = []os.FileInfo{stat}
		}
		for _, info := range files {
			if strings.HasSuffix(info.Name(), ".yml") || strings.HasSuffix(info.Name(), ".yaml") {
				fileName := path.Join(location, info.Name())
				data, err := ioutil.ReadFile(fileName)
				if err != nil {
					return nil, err
				}
				var conf = DefaultConfig()
				err = yaml.Unmarshal(data, &conf)
				if err != nil {
					return nil, err
				}
				ans.MergeFrom(&conf)
			}
		}
	}
	return ans, nil
}
